<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="询价单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billcode">
              <a-input v-model="model.billcode" disabled="true"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="城市/地区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cityid">
              <j-area-linkage type="cascader" v-model="model.cityid" placeholder="请输入省市区" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="地区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="regionid">
              <j-area-linkage type="cascader" v-model="model.regionid" placeholder="请输入省市区" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="车辆信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vehicle">
              <a-input v-model="model.vehicle" placeholder="请输入车辆信息"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="车牌号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="plate">
              <a-input v-model="model.plate" placeholder="请输入车牌号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="车架号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vin">
              <a-input v-model="model.vin" placeholder="请输入车架号"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="事故号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="accidentNumber">
              <a-input v-model="model.accidentNumber" placeholder="请输入事故号"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item label="配件数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partcount">
              <a-input-number disabled="true" v-model="model.partcount" placeholder="请输入配件数量" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="报案号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bah">
              <a-input v-model="model.bah" placeholder="请输入报案号"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item label="修理厂地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xlcaddress">
              <a-input v-model="model.xlcaddress" placeholder="请输入修理厂地址"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="修理厂联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xlclink">
              <a-input v-model="model.xlclink" placeholder="请输入修理厂联系方式"></a-input>
            </a-form-model-item>
          </a-col> -->
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="事故图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="accidentimagesString">
              <j-image-upload isMultiple v-model="model.accidentimagesString" :bizPath="imgsrc"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="行驶证图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="licenseimageString">
              <j-image-upload v-model="model.licenseimageString" @beforeUpload="handleOcr"></j-image-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- <a-row>
          <a-col :span="12" v-show="this.canshow">
            <a-form-model-item label="地区驳回意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="regionrejectreason">
              <a-textarea type="textarea" v-model="model.regionrejectreason" :rows="2" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-show="this.canshow">
            <a-form-model-item label="省公司驳回意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provicerejectreason">
              <a-textarea type="textarea" v-model="model.provicerejectreason" :rows="2" />
            </a-form-model-item>
          </a-col>
        </a-row> -->
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="询价单分录" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table keep-source :ref="refKeys[0]" :loading="scmxjditemTable.loading" :columns="scmxjditemTable.columns"
          :dataSource="scmxjditemTable.dataSource" :maxHeight="300" :rowNumber="true" :alwaysEdit="true"
          :rowSelection="true" :toolbar="false" @valueChange="handlepricevaluechange" :span-method="mergeRowMethod">
          <!-- <template slot="toolbarSuffix" :disabled="formDisabled">
            <a-button type="export" @click="exportDataEvent" :disabled="formDisabled">导出模板</a-button>
            <a-button @click="adjustqtyclick">批量调整配件数量</a-button>
            <a-button @click="adjustpzclick">批量调整配件品质</a-button>
            <a-upload :file-list="fileList" :customRequest="importDataEvent">
              <a-button :disabled="formDisabled"> <a-icon type="upload" /> 选择导入文件 </a-button>
            </a-upload>
          </template> -->
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import Area from '@/components/_util/Area'
import { postAction, postActionByOcr } from '../../../../../api/manage'

export default {
  name: 'ScmxjdForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      pjqty: 0,
      selectpz: '',
      pjpzadjustvisable: false,
      adjustqtyvisable: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        cityid: [{ required: true, message: '请选择地区!' }],
        vehicle: [{ required: true, message: '请选择车辆信息' }],
        vin: [{ required: true, message: '请选择车架号' }],
        plate: [{ required: true, message: '请选择车牌号' }],
        accidentNumber: [{ required: true, message: '请选择事故号' }]
      },
      filelist: [],
      canshow: true,
      refKeys: ['scmxjditem'],
      tableKeys: ['scmxjditem'],
      activeKey: 'scmxjditem',
      // 询价单分录
      scmxjditemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '配件编码',
            key: 'matcode',
            type: JVXETypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '配件名称',
            key: 'matname',
            type: JVXETypes.input,
            width: '200px',
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '配件数量',
            key: 'count',
            type: JVXETypes.inputNumber,
            width: '200px',
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remarks',
            type: JVXETypes.input,
            width: '200px',
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '配件品质',
            key: 'quality',
            type: JVXETypes.list_multi,
            dictCode: 'pjpz',
            width: '200px',
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },

          {
            title: '报价',
            key: "quoprice",
            type: JVXETypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0'
          },
          {
            title: '报价合计',
            key: "quotaxinvalue",
            type: JVXETypes.inputNumber,
            disabled: true,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '0',
            statistics: ['sum']
          },
          {
            title: "附加信息",
            key: "quoremarks",
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
          }
        ]
      },
      workbook: null,
      sheetNames: [],
      selectedSheet: '',
      sheetData: [],
      sumvalue: 0,
      url: {
        add: '/rfq.xbj/scmxjd/add',
        edit: '/rfq.xbj/scmxjd/edit',
        queryById: '/rfq.xbj/scmxjd/queryById',
        scmxjditem: {
          list: '/rfq.xbj/scmxjd/queryScmxjditemByMainIdNew'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled () {
      return this.disabled
    }
  },
  created () {

  },
  methods: {
    handlepricevaluechange (event) {
      let { type, value, oldvalue, row, col, column, rowIndex, columnIndex, cellTarget, isSetValues } = event;
      if (col.key === 'quoprice') {
        row['quotaxinvalue'] = value * row['count']
      }
    },
    mergeRowMethod ({ row, rowIndex, $rowIndex, _rowIndex, column, columnIndex, $columnIndex, _columnIndex, data }) {
      const fields = ['matcode', 'matname', 'count', 'remarks']
      const cellValue = row[column.own.key]
      if (cellValue && fields.includes(column.own.key)) {
        const prevRow = data[rowIndex - 1]
        let nextRow = data[rowIndex + 1]
        if (prevRow && prevRow[column.own.key] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[column.own.key] === cellValue) {
            nextRow = data[++countRowspan + rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    },
    getimgInfo (file) {
      return new Promise(resolve => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = ev => {
          resolve(ev.target.result)
        }
      })
    },
    async handleOcr (file) {
      let imgdata = await this.getimgInfo(file)
      postAction('/rfq.xbj/scmxjd/getxzsinfo', { img: imgdata }).then(res => {
        if (res) {
          if (res.result) {
            let resu = res.result
            console.log(resu)
            if (resu.error_msg == '') {
              let vehinfo = resu.front_result
              this.model.vehicle = vehinfo.car_model
              this.model.vin = vehinfo.vin_code
              this.model.plate = vehinfo.car_no
            }
          }
        }
      })
      return true
    },
    addBefore () {
      this.scmxjditemTable.dataSource = []
    },
    getAllTable () {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    async editAfter () {
      this.$nextTick(() => { })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        await this.requestSubTableData(this.url.scmxjditem.list, params, this.scmxjditemTable)
      } else {
        this.canshow = false
      }
    },
    //校验所有一对一子表表单
    validateSubForm (allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch(e => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData (allValues) {
      this.model = Object.assign(this.model, { fullcityname: this.pcaData.getText(this.model.cityid) })
      let formData = new FormData()
      formData.img = this.filelist
      this.model = Object.assign(this.model, { formdata: formData })
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        scmxjditemList: allValues.tablesValue[0].tableData
      }
    },
    validateError (msg) {
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped></style>
